package com.maszy.commons.tools;
/**
 * 
 */

/** 
 * @作者 Allen Shu 
 * @创建日期 2012-7-3 
 * @版本 V 1.0 
 */

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.print.Doc;
import javax.print.DocFlavor;
import javax.print.DocPrintJob;
import javax.print.PrintException;
import javax.print.PrintService;
import javax.print.PrintServiceLookup;
import javax.print.SimpleDoc;
import javax.print.attribute.DocAttributeSet;
import javax.print.attribute.HashDocAttributeSet;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.MediaSizeName;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JTable;
import javax.swing.table.TableModel;

import com.maszy.bean.Dept;
import com.maszy.bean.DoorStore;
import com.maszy.bean.GoodPlan;
import com.maszy.bean.Product;
import com.maszy.service.DeptService;
import com.maszy.service.DoorStoreService;
import com.maszy.service.GoodPlanService;
import com.maszy.service.ProductService;
 
/**
 *
 * @author xiaoquan
 */
public class PrintTableTest implements Printable {
 
    private TableModel model = null;
    private String info;
    private int totalRow = 0;
    private static final int LEFT = 0;
    private static final int RIGHT = 1;
    private static final int CENTER = 2;
    private static final int AUTO = 3;
    private static String deptName="0";
    private static String type;
    public void printTable(TableModel model,String info,String printName) {
        this.model = model;
        this.info = info;
        totalRow = model.getRowCount();
//        PrinterJob printJob = PrinterJob.getPrinterJob();
//        printJob.setPrintable(this);
//        if (printJob.printDialog()) {
//            try {
//                printJob.print();
//            } catch (Exception ex) {
//                ex.printStackTrace();
//            }
//        }
//        String printName = "Canon MP250";
        DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PRINTABLE;
		DocAttributeSet das = new HashDocAttributeSet();
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(
				flavor, das);
		for (int i = 0; i < printServices.length; i++) {
			 System.out.println("第"+(i+1)+"个打印机:"+printServices[i].getName()+"  printName:"+printName);
			if (printName.equals(printServices[i].getName())) {
				// 创建打印作业
				DocPrintJob job = printServices[i].createPrintJob();
				// 设置打印属性
				PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
				// 设置纸张大小,也可以新建MediaSize类来自定义大小
				pras.add(MediaSizeName.ISO_A4);

				// 指定打印内容
				Doc doc = new SimpleDoc(this, flavor, das);
				// 不显示打印对话框，直接进行打印工作
				try {
					job.print(doc, pras); // 进行每一页的具体打印操作
				} catch (PrintException pe) {
					pe.printStackTrace();
				}
			}
		}
    }
    private static final double paper_offset_x = 20;
    private static final double paper_offset_y = 20;
    private static final double title_time_margin = 10;
    private static final double time_body_margin = 2;
    private static final double cell_padding_y = 3;
    private static final double cell_padding_x = 2;
    private static final double body_btm_margin = 20;
    private static final double body_cell_height = 20;
    private static final Font title_font = new Font("宋体", Font.PLAIN, 18);
    private static final Font time_font = new Font("宋体", Font.PLAIN, 14);
    private static final Font body_font = new Font("宋体", Font.PLAIN, 14);
 
     
    public int print(Graphics g, PageFormat pf, int pageIndex) throws
            PrinterException {
        //纸张宽
        double pageWidth = pf.getImageableWidth();
        //纸张高
        double pageHeight = pf.getImageableHeight();
        //打印的内容起始X
        double pageStartX = pf.getImageableX();
        //打印的内容起始Y
        double pageStartY = pf.getImageableY();
 
        //表头高
        double tableHeadH = 0;
        //Cell高
        double cellH = 0;
 
        //计算表头高度和单元格高度
        g.setFont(body_font);
        FontMetrics cellFm = g.getFontMetrics();
        cellH = cellFm.getHeight() + cell_padding_y * 2 + 1;
        tableHeadH = cellH * 2;
 
        //计算Title以及其位置
        String title = info;
        g.setFont(title_font);
        FontMetrics titleFm = g.getFontMetrics();
        int titleW = titleFm.stringWidth(title);
 
        //表底和表头文字属性
        g.setFont(time_font);
        FontMetrics btmFm = g.getFontMetrics();
        FontMetrics timeFm = g.getFontMetrics();
 
        //表格以上的Margin
        double tableTopMargin = paper_offset_y + titleFm.getHeight() +
                title_time_margin + timeFm.getHeight() + time_body_margin;
 
        //表格每列的最大宽度
        double[] cellColMaxWidths = caculateTableCellWidth(model, cellFm);
 
        //当前Page的数据容量高度-不包括表头和表尾
        double currentPageDataCapacityHeight = pageHeight - tableTopMargin -
                tableHeadH - btmFm.getHeight() - body_btm_margin - 1;
 
        //当前Page的数据容量
        int currentPageBodyCapacityRows = (int) (currentPageDataCapacityHeight /
                cellH);
 
        //Y方向的分页数量
        int pagesY = 0;
        if (model.getRowCount() % currentPageBodyCapacityRows == 0) {
            pagesY = (int) (model.getRowCount() /
                    currentPageBodyCapacityRows);
        } else {
            pagesY = (int) (model.getRowCount() /
                    currentPageBodyCapacityRows) +
                    1;
        }
 
        //当前页数大于总页数时不打印
        if (pageIndex + 1 > pagesY) {
            return NO_SUCH_PAGE;
        }
 
        //绘制Title
        g.setFont(title_font);
        g.drawString(title, (int) (pageStartX +
                (pageWidth - titleW) / 2), (int) (pageStartY +
                paper_offset_y +
                titleFm.getAscent()));
 
        //绘制区域移动到新的(0,0)点
        g.translate((int) (paper_offset_x + pageStartX), (int) (tableTopMargin +
                pageStartY));
        int currentX = 0, currentY = 0;
 
        //绘制第一张表
 
        //绘制表头
        g.setFont(time_font);
        String date = new SimpleDateFormat("yyyy-MM-dd").format(Calendar
				.getInstance().getTime());
        String time = deptName+"               第"+(pageIndex + 1)+"页，共"+pagesY+"页                     "+date;
        g.drawString(time, currentX, currentY);
        currentY += 5;
        //绘制单一表头
        for (int i = 0; i < model.getColumnCount(); i++) {
            double width = cellColMaxWidths[i];
            double height = tableHeadH;
            String name = model.getColumnName(i);
            drawCell(g, name, currentX, currentY, (int) width,
                    (int) height, CENTER);
            currentX += width;
        }
 
        //绘制数据
        currentX = 0;
        currentY = (int) tableHeadH;
        //当前Page的数据容量
        int rightCellX = 0;
        int yIndex = pageIndex;
        int startRow = currentPageBodyCapacityRows * yIndex;
        int endRow = (currentPageBodyCapacityRows * (yIndex + 1)) >  //aa
                totalRow
                ? totalRow
                : (currentPageBodyCapacityRows * (yIndex + 1));
        for (int row = startRow; row < endRow; row++) {
            //绘制单项表头下面的数据
            for (int i = 0; i < model.getColumnCount(); i++) {
                double width = cellColMaxWidths[i];
                double height = body_cell_height;
                Object value = model.getValueAt(row, i);
                drawCell(g, value, currentX, currentY, (int) width,
                        (int) height, AUTO);
                currentX += width;
                rightCellX = currentX;
            }
            currentX = 0;
            currentY += cellH;
        }
 
        //绘制闭合线，下面和右侧两条
        g.drawLine(currentX, currentY, rightCellX, currentY);
        g.drawLine(rightCellX, 5, rightCellX, currentY);
 
       // drawBottomInfo(pageIndex, pagesY, currentY, g, (int) pageWidth);
        return PAGE_EXISTS;
    }
 
    private void drawBottomInfo(int pageIndex, int pagesY,
            int currentY, Graphics g, int pageWidth) {
        if (pageIndex + 1 == pagesY) {
            //绘制底部信息
            int btmX = 0;
            int btmY = currentY + 20;
            g.drawString("负责人:", btmX, btmY);
            g.drawString("制表:", pageWidth / 3, btmY);
            FontMetrics fm = g.getFontMetrics();
            int dataWidth = fm.stringWidth("日期: 2009/10/26");
            g.drawString("日期:", pageWidth - dataWidth, btmY);
        }
    }
 
    /**
     * 计算最大列宽
     * @param cellFm
     * @return
     */
    private double[] caculateTableCellWidth(
            TableModel model,
            FontMetrics cellFm) {
        //表格每列的最大宽度
        double[] cellColMaxWidths = new double[model.getColumnCount()];
 
        //计算表头每列最大宽度
        double[] headerColMaxWidths = new double[model.getColumnCount()];
 
        for (int i = 0; i < model.getColumnCount(); i++) {
            String name = model.getColumnName(i);
            headerColMaxWidths[i] = cellFm.stringWidth(name) + cell_padding_x *
                    2 + 1;
        }
        //没有数据时，表头每列的最大宽度就是表格每列的最大宽度
        cellColMaxWidths = headerColMaxWidths;
        System.out.println(model.getRowCount()+"\t"+model.getColumnCount());
        
        //算数据每列的最大宽度和表头每列最大宽度对比
        for (int j = 0; j < model.getRowCount(); j++) {
            for (int i = 0; i < model.getColumnCount(); i++) {
                //做些数据类型的判断
                Object value = model.getValueAt(j, i);
                if (value instanceof BigDecimal) {
                    value = ((BigDecimal) value).doubleValue();
                }
                String text = "";
                if (value != null) {
                    text = value.toString();
                }
                double temp = cellFm.stringWidth(text) + cell_padding_x * 2 + 1;
                if (cellColMaxWidths[i] < temp) {
                    cellColMaxWidths[i] = temp;
                }
            }
        }
        return cellColMaxWidths;
    }
 
    /**
     * 绘制单元格及里面的文字
     * @param g
     * @param value
     * @param x
     * @param y
     * @param width
     * @param height
     */
    private static void drawCell(Graphics g, Object value, int x, int y,
            int width,
            int height, int locate) {
        g.drawLine(x, y, x + width - 1, y);
        g.drawLine(x, y, x, y + height - 1);
        FontMetrics fm = g.getFontMetrics();
        if (value == null) {
            value = "";
        }
        switch (locate) {
            case 0:
                //居左
                g.drawString(value.toString(), (int) (x + cell_padding_x), y +
                        (height - fm.getHeight()) / 2 + fm.getAscent());
            case 1:
                //居右
                g.drawString(value.toString(),
                        (int) (x +
                        (width - fm.stringWidth(value.toString()) + width -
                        fm.stringWidth(value.toString()) - cell_padding_x) /
                        2), y +
                        (height - fm.getHeight()) / 2 + fm.getAscent());
            case 2:
                //居中
                g.drawString(value.toString(), x + (width - fm.stringWidth(
                        value.toString())) / 2, y + (height -
                        fm.getHeight()) / 2 + fm.getAscent());
            case 3:
                //自动判断
                NumberFormat formatter = NumberFormat.getNumberInstance();
                formatter.setMinimumFractionDigits(2);
                formatter.setMaximumFractionDigits(2);
                //根据数据类型左对齐还是右对齐绘制还是居中对齐
                if (value instanceof BigDecimal) {
                    //居右
                    value = ((BigDecimal) value).doubleValue();
                    value = formatter.format(value);
                    g.drawString(value.toString(),
                            (int) (x +
                            (width - fm.stringWidth(value.toString()) + width -
                            fm.stringWidth(value.toString()) - cell_padding_x) /
                            2), y +(height - fm.getHeight()) / 2 + fm.getAscent());
                } else if (value instanceof Integer || value instanceof Long ||
                        value instanceof Double) {
                    //居右
                    g.drawString(value.toString(),
                            (int) (x +
                            (width - fm.stringWidth(value.toString()) + width -
                            fm.stringWidth(value.toString()) - cell_padding_x) /
                            2), y +
                            (height - fm.getHeight()) / 2 + fm.getAscent());
                } else {
                    //居中
                    g.drawString(value.toString(), x + (width - fm.stringWidth(
                            value.toString())) / 2, y + (height -
                            fm.getHeight()) / 2 + fm.getAscent());
                }
        }
    }
    public void printReport1(){
    	DeptService deptService=new DeptService();
		List<Dept> deptList=deptService.queryAllAndCountProduct();
		for(int q=0;q<deptList.size();q++){
			if(deptList.get(q).getCountProduct()>0){
				this.deptName=deptList.get(q).getDept_name();
				PrintTableTest pt=new PrintTableTest();
				System.out.println("开始统计"+this.deptName);
				System.out.println("---------------------------------------------------------------------------------");
				try{
					TableModel model= pt.queryReport1();
					pt.printTable(model, "原材料汇总单", deptList.get(q).getPrint_name());
				}catch(Exception e){
					e.printStackTrace();
				}
				
			}
		}		
    }
	
	public static void main(String[] args) {
//        new PrintTableTest().printTable(testData(), "测试", "print2");
    	PrintTableTest pt=new PrintTableTest();
    	pt.printReport1();
    }
	private TableModel queryReport1() {
		Object[] body = null;
		GoodPlan obj=new GoodPlan();
//		String date=new SimpleDateFormat("yyyy-MM-dd").format(Calendar
//				.getInstance().getTime());
		String yesterday = new SimpleDateFormat("yyyy-MM-dd")
		.format(new Date(System.currentTimeMillis() - 1000 * 60
				* 60 * 24));// 获取昨天日期
		obj.setGoodPlan_BeginDate(yesterday+" 00:00:00");
		obj.setGoodPlan_EndDate(yesterday+" 23:59:59");
//		obj.setGoodPlan_BeginDate("2012-06-14"+" 00:00:00");
//		obj.setGoodPlan_EndDate("2012-06-14"+" 23:59:59");
		obj.setGoodPlan_Type("1");
		//先获取所有门店的信息
		DoorStoreService doorStoreService=new DoorStoreService();
		List<DoorStore> doorStoreList=doorStoreService.queryAll();
		for(int i=0;i<doorStoreList.size();i++){
			if(doorStoreList.get(i).getDoorStore_Id()==1){
				doorStoreList.remove(i);
			}
		}
		Object[] arr = (Object[])doorStoreList.toArray(new Object[doorStoreList.size()+2]);
		arr[0]="品名";
		arr[doorStoreList.size()+1]="合计";
		for(int i=0;i<doorStoreList.size();i++){
			arr[i+1]=doorStoreList.get(i).getDoorStore_Name();
		}
//		for(int iii=0;iii<arr.length;iii++){
//			System.out.println(arr[iii]);
//		}
		//获取所有产品信息
		ProductService productService=new ProductService();
		List<Product>  productList=productService.queryAll();
		//查询当日所有门店的原材料供应单的报表情况.
		GoodPlanService goodPlanService=new GoodPlanService();
		List<GoodPlan> goodPlanList=goodPlanService.queryOneDayGoodPlan1(obj);
		//先循环出所有单品
		List<String[]> list=new ArrayList<String[]>();
		
		for(int i=0;i<productList.size();i++){
			if (productList.get(i).getProduct_Dept_Name().equals(this.deptName)) {
			List<Object> reportItemList=new ArrayList<Object>();
			reportItemList.add(productList.get(i).getProduct_Name());
			int sum=0;
			LabelA:
				//循环出所有门店
			for(int j=0;j<doorStoreList.size();j++){
				boolean b=false;
				LabelB:
					//循环所有要货计划表头
					for(int m=0;m<goodPlanList.size();m++){
						//判断要货计划里是否有该门店
						if(goodPlanList.get(m).getDoorStore_Id().equals(doorStoreList.get(j).getDoorStore_Id())){
							//如果有该门店.循环这家门店要货计划明细数据
							List<Product> planBodyList=goodPlanList.get(m).getProductList();
							LabelC:
							for(int o=0;o<planBodyList.size();o++){
								//如果要货明细里和单品对应上,则把数量加进去,否则显示0
								if(productList.get(i).getProduct_Id().equals(planBodyList.get(o).getProduct_Id())){
									reportItemList.add(planBodyList.get(o).getProduct_Quantity());
									sum+=Integer.parseInt(planBodyList.get(o).getProduct_Quantity());
									b=true;
								//	System.out.println(planBodyList.get(o).getProduct_Name()+"  "+planBodyList.get(o).getProduct_Quantity());
									break LabelB;
								}
							}
						}
					}
				if(b==false){
					reportItemList.add("0");
				}
			}
			reportItemList.add(Integer.toString(sum));
			if(sum>0){
				body = (String[])reportItemList.toArray(new String[reportItemList.size()]);
				for(int iii=0;iii<reportItemList.size();iii++){
					body[iii]=reportItemList.get(iii);
				}
				list.add((String[])body);
			}
			}
		}
		Object rows[][] = new Object[list.size()][body.length];
		for(int i=0;i<list.size();i++){
			rows[i]=list.get(i);
		}
		for(int m=0;m<rows.length;m++){
			System.out.println(m+"-------------------------------------------------------------------------------------");
			for(int n=0;n<rows[m].length;n++){
				System.out.print(rows[m][n]+"\t");
			}
			System.out.println();
			System.out.println("-----------------------------------------------------------------------------------------");
		}
		JTable table = new JTable(rows, arr);
		return table.getModel();
	}
	
}

